import 'package:chat_bottom_container/chat_bottom_container.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:life_service/color/hex.dart';
import 'package:life_service/extensions/ex_widget.dart';
import 'package:life_service/utils/styles.dart';
import 'package:life_service/utils/tools.dart';

import 'controller.dart';

class CustomerChatPage extends GetView<CustomerChatController> {
  const CustomerChatPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(Get.mediaQuery.padding.top + 44),
        child: AnnotatedRegion<SystemUiOverlayStyle>(
          value: SystemUiOverlayStyle.dark,
          child: Container(
            padding: Get.mediaQuery.padding,
            alignment: Alignment.centerLeft,
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                bottom: BorderSide(
                  color: HexColor(HexColor.colorF2f2),
                ),
              ),
            ),
            child: TextButton(
              onPressed: Get.back,
              child: Text.rich(
                TextSpan(
                  children: [
                    const WidgetSpan(
                      child: Icon(
                        CupertinoIcons.chevron_back,
                        size: 18,
                        color: Colors.black,
                      ),
                    ),
                    TextSpan(
                      text: ' 客服',
                      style: StylesUtils.customTextStyle(
                        fontSize: StylesUtils.fontSize16,
                        color: HexColor.color3333,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
      body: const ChatPage(),
    );
  }
}

enum PanelType {
  none,
  keyboard,
  emoji,
  tool,
}

class ChatPage extends StatefulWidget {
  const ChatPage({
    super.key,
    this.safeAreaBottom,
    this.showAppBar = true,
    this.changeKeyboardPanelHeight,
    this.onControllerCreated,
  });

  final double? safeAreaBottom;

  final bool showAppBar;

  final ChatKeyboardChangeKeyboardPanelHeight? changeKeyboardPanelHeight;

  final Function(ChatBottomPanelContainerController)? onControllerCreated;

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> with RouteAware {
  Color panelBgColor = const Color(0xFFF5F5F5);

  final FocusNode inputFocusNode = FocusNode();

  final controller = ChatBottomPanelContainerController<PanelType>();

  PanelType currentPanelType = PanelType.none;

  bool readOnly = false;

  final routeObserver = RouteObserver<ModalRoute>();

  bool isInput = false;

  final editingController = ToolsUtils.editingController('');

  List<Widget> sends = [];

  final scrollController = ScrollController();

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context)!);
  }

  @override
  void initState() {
    super.initState();
    editingController.addListener(() {
      isInput = false;
      if (editingController.text.isNotEmpty) {
        isInput = true;
      }
      setState(() {});
    });
    widget.onControllerCreated?.call(controller);
  }

  @override
  void dispose() {
    inputFocusNode.dispose();
    routeObserver.unsubscribe(this);
    editingController.dispose();
    scrollController.dispose();
    super.dispose();
  }

  @override
  void didPushNext() {
    super.didPushNext();
    hidePanel();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(child: _buildList()),
        _buildInputView(),
        _buildPanelContainer(),
      ],
    );
  }

  Widget _buildList() {
    return Listener(
      child: ListView(
        padding: const EdgeInsets.symmetric(horizontal: 20),
        controller: scrollController,
        children: [
          Container(
            padding: const EdgeInsets.only(top: 15),
            alignment: Alignment.center,
            child: Text(
              DateFormat('HH:mm').format(DateTime.now()),
              style: StylesUtils.customTextStyle(
                color: HexColor.color3333,
                fontSize: StylesUtils.fontSize12,
              ),
            ),
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              const CircleAvatar(
                radius: 17,
                backgroundImage: NetworkImage(
                    'https://img0.baidu.com/it/u=920698175,381618341&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800'),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 10),
                child: ConstrainedBox(
                  constraints: const BoxConstraints(
                    maxWidth: 290,
                    minHeight: 46,
                  ),
                  child: LayoutBuilder(builder: (ctx, c) {
                    String text = '您好，请问有什么可以帮您';
                    final style = StylesUtils.customTextStyle(
                      lineHeight: 1.4,
                      color: HexColor.color3333,
                      fontSize: StylesUtils.fontSize13,
                    );
                    final w = ToolsUtils.calculateTextWidth(
                        value: text, style: style);
                    return Container(
                      width: w + 40,
                      alignment: Alignment.centerLeft,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 15, vertical: 10),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: const BorderRadius.only(
                          topRight: Radius.circular(16),
                          bottomLeft: Radius.circular(16),
                          bottomRight: Radius.circular(16),
                        ),
                        boxShadow: [
                          BoxShadow(
                            offset: Offset.zero,
                            blurRadius: 10,
                            spreadRadius: 0,
                            blurStyle: BlurStyle.outer,
                            color: HexColor.rgba(204, 204, 204, 0.4),
                          )
                        ],
                      ),
                      child: Text(
                        text,
                        style: style,
                      ),
                    );
                  }),
                ),
              ),
            ],
          ).paddingOnly(top: 15),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: const EdgeInsets.only(right: 10),
                child: ConstrainedBox(
                  constraints: const BoxConstraints(
                    maxWidth: 290,
                    minHeight: 46,
                  ),
                  child: LayoutBuilder(builder: (ctx, c) {
                    String text = '你好，我想问下付款后多久酒店这边可以确认成功呢';
                    final style = StylesUtils.customTextStyle(
                      lineHeight: 1.4,
                      color: HexColor.colorFf62,
                      fontSize: StylesUtils.fontSize13,
                    );
                    final w = ToolsUtils.calculateTextWidth(
                        value: text, style: style);
                    return Container(
                      width: w + 120,
                      alignment: Alignment.centerLeft,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 15, vertical: 10),
                      decoration: BoxDecoration(
                        color: HexColor('#FFE2E2'),
                        borderRadius: const BorderRadius.only(
                          topLeft: Radius.circular(16),
                          bottomLeft: Radius.circular(16),
                          bottomRight: Radius.circular(16),
                        ),
                        boxShadow: [
                          BoxShadow(
                            offset: Offset.zero,
                            blurRadius: 10,
                            spreadRadius: 0,
                            blurStyle: BlurStyle.outer,
                            color: HexColor.rgba(204, 204, 204, 0.4),
                          )
                        ],
                      ),
                      child: Text(
                        text,
                        style: style,
                      ),
                    );
                  }),
                ),
              ),
              const CircleAvatar(
                radius: 17,
                backgroundImage: NetworkImage(
                    'https://img0.baidu.com/it/u=1690076377,4003691410&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500'),
              ),
            ],
          ).paddingOnly(top: 15),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              const CircleAvatar(
                radius: 17,
                backgroundImage: NetworkImage(
                    'https://img0.baidu.com/it/u=920698175,381618341&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800'),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 10),
                child: ConstrainedBox(
                  constraints: const BoxConstraints(
                    maxWidth: 290,
                    minHeight: 46,
                  ),
                  child: LayoutBuilder(builder: (ctx, c) {
                    String text = '具体要看酒店的人员安排呢';
                    final style = StylesUtils.customTextStyle(
                      lineHeight: 1.4,
                      color: HexColor.color3333,
                      fontSize: StylesUtils.fontSize13,
                    );
                    final w = ToolsUtils.calculateTextWidth(
                        value: text, style: style);
                    return Container(
                      width: w + 40,
                      alignment: Alignment.centerLeft,
                      padding: const EdgeInsets.symmetric(
                          vertical: 10, horizontal: 15),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: const BorderRadius.only(
                          topRight: Radius.circular(16),
                          bottomLeft: Radius.circular(16),
                          bottomRight: Radius.circular(16),
                        ),
                        boxShadow: [
                          BoxShadow(
                            offset: Offset.zero,
                            blurRadius: 10,
                            spreadRadius: 0,
                            blurStyle: BlurStyle.outer,
                            color: HexColor.rgba(204, 204, 204, 0.4),
                          )
                        ],
                      ),
                      child: Text(
                        text,
                        style: style,
                      ),
                    );
                  }),
                ),
              ),
            ],
          ).paddingOnly(top: 15),
          ...sends,
        ],
      ),
      onPointerDown: (event) {
        // Hide panel when touch ListView.
        hidePanel();
      },
    );
  }

  Widget _buildPanelContainer() {
    return ChatBottomPanelContainer<PanelType>(
      controller: controller,
      inputFocusNode: inputFocusNode,
      otherPanelWidget: (PanelType? type) {
        if (type == null) return const SizedBox.shrink();
        switch (type) {
          case PanelType.emoji:
            return _buildEmojiPickerPanel();
          case PanelType.tool:
            return _buildToolPanel();
          default:
            return const SizedBox.shrink();
        }
      },
      onPanelTypeChange: (panelType, data) {
        debugPrint('panelType: $panelType');
        switch (panelType) {
          case ChatBottomPanelType.none:
            currentPanelType = PanelType.none;
            break;
          case ChatBottomPanelType.keyboard:
            currentPanelType = PanelType.keyboard;
            break;
          case ChatBottomPanelType.other:
            if (data == null) return;
            switch (data) {
              case PanelType.emoji:
                currentPanelType = PanelType.emoji;
                break;
              case PanelType.tool:
                currentPanelType = PanelType.tool;
                break;
              default:
                currentPanelType = PanelType.none;
                break;
            }
            break;
        }
      },
      changeKeyboardPanelHeight: widget.changeKeyboardPanelHeight,
      panelBgColor: panelBgColor,
      safeAreaBottom: widget.safeAreaBottom,
    );
  }

  Widget _buildToolPanel() {
    return Container(
      height: 400,
      color: Colors.red[50],
      child: const Center(
        child: Text('Tool Panel'),
      ),
    );
  }

  Widget _buildEmojiPickerPanel() {
    // If the keyboard height has been recorded, priority is given to setting
    // the height to the keyboard height.
    double height = 300;
    final keyboardHeight = controller.keyboardHeight;
    if (keyboardHeight != 0) {
      if (widget.changeKeyboardPanelHeight != null) {
        height = widget.changeKeyboardPanelHeight!.call(keyboardHeight);
      } else {
        height = keyboardHeight;
      }
    }

    return Container(
      padding: EdgeInsets.zero,
      height: height,
      color: Colors.blue[50],
      child: const Center(
        child: Text('Emoji Panel'),
      ),
    );
  }

  Widget _buildInputView() {
    return Container(
      height: 50,
      color: Colors.white,
      child: Row(
        children: [
          const SizedBox(width: 15),
          Expanded(
            child: Listener(
              onPointerUp: (event) {
                // Currently it may be emojiPanel.
                if (readOnly) {
                  updatePanelType(PanelType.keyboard);
                }
              },
              child: TextField(
                focusNode: inputFocusNode,
                readOnly: readOnly,
                showCursor: true,
                controller: editingController,
                style: StylesUtils.customTextStyle(
                  color: HexColor.color0000,
                  fontSize: StylesUtils.defaultFontSize,
                ),
                decoration: InputDecoration(
                  constraints:
                      const BoxConstraints.expand(width: 200, height: 40),
                  suffixIconConstraints:
                      const BoxConstraints.expand(width: 85, height: 40),
                  suffixIcon: TextButton(
                    onPressed: () {
                      String text = editingController.text;
                      isInput = false;
                      editingController.text = '';
                      sends.add(
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Padding(
                              padding: const EdgeInsets.only(right: 10),
                              child: ConstrainedBox(
                                constraints: const BoxConstraints(
                                  maxWidth: 290,
                                  minHeight: 46,
                                ),
                                child: LayoutBuilder(builder: (ctx, c) {
                                  final style = StylesUtils.customTextStyle(
                                    lineHeight: 1.4,
                                    color: HexColor.colorFf62,
                                    fontSize: StylesUtils.fontSize13,
                                  );
                                  final w = ToolsUtils.calculateTextWidth(
                                      value: text, style: style);
                                  return Container(
                                    width: w + 40,
                                    alignment: Alignment.centerLeft,
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 15, vertical: 10),
                                    decoration: BoxDecoration(
                                      color: HexColor('#FFE2E2'),
                                      borderRadius: const BorderRadius.only(
                                        topLeft: Radius.circular(16),
                                        bottomLeft: Radius.circular(16),
                                        bottomRight: Radius.circular(16),
                                      ),
                                      boxShadow: [
                                        BoxShadow(
                                          offset: Offset.zero,
                                          blurRadius: 10,
                                          spreadRadius: 0,
                                          blurStyle: BlurStyle.outer,
                                          color:
                                              HexColor.rgba(204, 204, 204, 0.4),
                                        )
                                      ],
                                    ),
                                    child: Text(
                                      text,
                                      style: style,
                                    ),
                                  );
                                }),
                              ),
                            ),
                            const CircleAvatar(
                              radius: 17,
                              backgroundImage: NetworkImage(
                                  'https://img0.baidu.com/it/u=1690076377,4003691410&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500'),
                            ),
                          ],
                        ).paddingOnly(top: 15),
                      );
                      setState(() {
                        Get.engine.addPostFrameCallback((_) {
                          scrollController.animateTo(
                              scrollController.position.maxScrollExtent,
                              duration: const Duration(milliseconds: 200),
                              curve: Curves.linear);
                        });
                      });
                    },
                    style: ButtonStyle(
                      minimumSize: const WidgetStatePropertyAll(Size(70, 30)),
                      fixedSize: const WidgetStatePropertyAll(Size(70, 30)),
                      backgroundColor: WidgetStatePropertyAll(
                        isInput
                            ? HexColor(HexColor.colorFf62)
                            : HexColor.rgba(255, 98, 98, 0.227450980392157),
                      ),
                      shape: WidgetStatePropertyAll(
                        RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(15),
                        ),
                      ),
                      alignment: Alignment.center,
                      foregroundColor:
                          const WidgetStatePropertyAll(Colors.transparent),
                    ),
                    child: Text(
                      '发送',
                      style: StylesUtils.customTextStyle(
                        fontSize: StylesUtils.fontSize12,
                      ),
                    ),
                  ).center(),
                  filled: true,
                  fillColor: HexColor.rgba(153, 153, 255, 0.0196078431372549),
                  hintText: '',
                  hintStyle: StylesUtils.customTextStyle(
                    color: HexColor.color9999,
                    fontSize: StylesUtils.fontSize13,
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(20),
                    borderSide: BorderSide(
                      color: HexColor(HexColor.colorF2f2),
                    ),
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(20),
                    borderSide: BorderSide(
                      color: HexColor(HexColor.colorF2f2),
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(20),
                    borderSide: BorderSide(
                      color: HexColor(HexColor.colorF2f2),
                    ),
                  ),
                  isCollapsed: true,
                  isDense: true,
                  contentPadding: const EdgeInsets.only(top: 15, left: 20),
                ),
              ),
            ),
          ),
          GestureDetector(
            child: const Icon(Icons.emoji_emotions_outlined, size: 30),
            onTap: () {
              updatePanelType(
                PanelType.emoji == currentPanelType
                    ? PanelType.keyboard
                    : PanelType.emoji,
              );
            },
          ),
          GestureDetector(
            child: const Icon(Icons.add, size: 30),
            onTap: () {
              updatePanelType(
                PanelType.tool == currentPanelType
                    ? PanelType.keyboard
                    : PanelType.tool,
              );
            },
          ),
          const SizedBox(width: 15),
        ],
      ),
    );
  }

  updatePanelType(PanelType type) async {
    final isSwitchToKeyboard = PanelType.keyboard == type;
    final isSwitchToEmojiPanel = PanelType.emoji == type;
    bool isUpdated = false;
    switch (type) {
      case PanelType.keyboard:
        updateInputView(isReadOnly: false);
        break;
      case PanelType.emoji:
        isUpdated = updateInputView(isReadOnly: true);
        break;
      default:
        break;
    }

    updatePanelTypeFunc() {
      controller.updatePanelType(
        isSwitchToKeyboard
            ? ChatBottomPanelType.keyboard
            : ChatBottomPanelType.other,
        data: type,
        forceHandleFocus: isSwitchToEmojiPanel
            ? ChatBottomHandleFocus.requestFocus
            : ChatBottomHandleFocus.none,
      );
    }

    if (isUpdated) {
      // Waiting for the input view to update.
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        updatePanelTypeFunc();
      });
    } else {
      updatePanelTypeFunc();
    }
  }

  hidePanel() {
    if (inputFocusNode.hasFocus) {
      inputFocusNode.unfocus();
    }
    updateInputView(isReadOnly: false);
    if (ChatBottomPanelType.none == controller.currentPanelType) return;
    controller.updatePanelType(ChatBottomPanelType.none);
  }

  bool updateInputView({
    required bool isReadOnly,
  }) {
    if (readOnly != isReadOnly) {
      readOnly = isReadOnly;
      // You can just refresh the input view.
      setState(() {});
      return true;
    }
    return false;
  }
}
